import * as THREE from "../../../modules/three/three.module.js";
import RoutePointVO, {OffsetEnum} from "./RoutePointVO.js";
import {mapCodeToCssColor} from "../lib/CommonConsts.js";
import {defaultAreaColor, defaultAreaColorCode} from "../lib/util/StaticMethods.js";

let routeCount = 0;
function setRouteCount(num) {
  if (routeCount <= num) {
    routeCount = num + 1;
  }
}

export default class RouteVO {
  id = 0;
  name = '';
  /**
   * 无人机航线的航点序列
   * @type {RoutePointVO[]}
   */
  pointsByJson = [];
  /**
   * 无人机航线的航点网格序列
   * @type {RoutePointIndicator[]}
   */
  pointMeshes = [];
  // 航线速度 地位 米/秒
  speed = 0.5;
  // 离墙距离
  sprayDistance = 2;
  /**
   * 航线的立邦喷漆颜色编码
   * @see {mapColorCssToCode}
   */
  colorCode = defaultAreaColorCode;
  routeOrder = 0;

  constructor() {
    this.id = routeCount++
  }
  getPaintColor() {
    return mapCodeToCssColor.get(this.colorCode) || defaultAreaColor;
  }
  getPointRadius() {
    if (!this.pointMeshes.length) {
      return 0.5;
    }
    return this.pointMeshes[0].vo.radius;
  }
  getOffsetType() {
    if (!this.pointMeshes.length) {
      return OffsetEnum.h
    }
    return this.pointMeshes[0].vo.offsetType
  }
  // 修改每个航点的半径
  updateRoutePointRadius(radius) {
    if (radius <= 0.01) {
      return;
    }
    this.pointMeshes.forEach((it) => it.updateRadius(radius));
  }

  editSpeed(speed) {
    this.speed = speed;
  }

  editSprayDistance(distance) {
    this.sprayDistance = distance;
  }
  removePointMesh(pointMesh) {
    const index = this.pointMeshes.indexOf(pointMesh)
    if (index >= 0) {
      this.pointMeshes.splice(index, 1)
    }
    return index
  }
  // 修改航线的喷漆颜色
  changeColorCode(colorCode) {
    const cssColor = mapCodeToCssColor.get(colorCode);
    if (!cssColor) {
      return;
    }
    this.colorCode = colorCode;
    this.pointMeshes.forEach((it) => it.changeColor(cssColor));
  }

  toJsonObj() {
    const obj = { id: this.id, name: this.name, speed: this.speed, sprayDistance: this.sprayDistance };
    obj.points = this.pointMeshes.map((it) => it.vo.toJsonObj());
    obj.colorCode = this.colorCode;
    return obj;
  }

  fromJsonObj(jsonObj) {
    const id = parseInt(jsonObj.id) || 0;
    setRouteCount(id);
    this.id = id;
    this.name = jsonObj.name;
    this.speed = jsonObj.speed;
    this.sprayDistance = jsonObj.sprayDistance || 2;
    this.colorCode = jsonObj.colorCode || defaultAreaColorCode;
    this.pointsByJson = jsonObj.points.map((it) =>
      new RoutePointVO().fromJsonObj(it),
    );
    return this;
  }
}
